<template>
  <el-dialog title="删除物资信息" :visible.sync="localVisible" @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="设备型号" prop="model">
        <el-input v-model="form.model" @blur="fetchMaterial"></el-input>
      </el-form-item>
      <el-form-item label="设备类型" prop="type">
        <el-input v-model="form.type" disabled></el-input>
      </el-form-item>
      <el-form-item label="设备厂商" prop="manufacturer">
        <el-input v-model="form.manufacturer" disabled></el-input>
      </el-form-item>
      <el-form-item label="设备使用区域" prop="area">
        <el-input v-model="form.area" disabled></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleDelete">删除</el-button>
    </div>
  </el-dialog>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      localVisible: this.visible,
      form: {
        model: '',
        type: '',
        manufacturer: '',
        area: ''
      },
      rules: {
        model: [{ required: true, message: '请输入设备型号', trigger: 'blur' }]
      }
    };
  },
  watch: {
    visible(newVal) {
      this.localVisible = newVal;
    },
    localVisible(newVal) {
      this.$emit('update:visible', newVal);
    },

  },
  methods: {
    handleClose() {
      this.localVisible = false;
    },
    fetchMaterial() {
      axios.post(`/api/stock/searchOne`, this.form.model, {
        headers: {
          'Content-Type': 'text/plain'
        }
      }).then((response) => {
        if (response.data.success) {
          Object.assign(this.form, response.data.data);
        } else {
          this.$message.error('该物资信息不存在');
        }
      }).catch((error) => {
        this.$message.error('查询失败');
      });
    },
    handleDelete() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios.post('/api/stock/delete', this.form.model, {
            headers: {
              'Content-Type': 'text/plain'
            }
          }).then((response) => {
            if (response.data.success) {
              this.$message.success('删除成功');
              this.handleClose();
            } else {
              this.$message.error('删除失败');
            }
          }).catch((error) => {
            this.$message.error('删除失败');
          });
        }
      });
    }
  }
};
</script>